/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.mall.biz.user.controller;

import co.yixiang.common.core.annotation.AnonymousAccess;
import co.yixiang.common.mproot.dozer.service.IGenerator;
import co.yixiang.mall.biz.user.service.YxMemberService;
import cn.hutool.core.util.ObjectUtil;
import co.yixiang.mall.biz.user.service.YxSystemUserTaskService;
import co.yixiang.mall.biz.user.service.YxUserService;
import co.yixiang.common.log.annotation.Log;
import co.yixiang.mall.common.mall.domain.YxSystemUserTask;
import co.yixiang.mall.common.mall.domain.YxUser;
import co.yixiang.mall.common.mall.dto.UserMoneyDto;
import co.yixiang.mall.common.mall.dto.YxMemberRankingQueryCriteria;
import co.yixiang.mall.common.mall.dto.YxUserQueryCriteria;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hupeng
 * @date 2019-10-06
 */
@Api(tags = "商城:会员管理")
@RestController
@RequestMapping
public class MemberController {

    @Autowired
    private YxSystemUserTaskService yxSystemUserTaskService;

    private final YxUserService yxUserService;

    private final YxMemberService memberService;
    private final IGenerator generator;


    public MemberController(YxUserService yxUserService, YxMemberService memberService, IGenerator generator) {
        this.yxUserService = yxUserService;
        this.memberService = memberService;
        this.generator = generator;
    }


    @Log("查看下级")
    @ApiOperation(value = "查看下级")
    @GetMapping(value = "/yxUser/spread")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity getSpread(@RequestParam("uid") String uid,@RequestParam("status") String status) {
        System.err.println("================================");
        System.err.println(uid);
        System.err.println(status);
        //JSON.stringify(uid);

        /*之前的方法
         * @RequestBody YxUserQueryCriteria criteria
         * yxUserService.querySpread(criteria.getUid(), criteria.getGrade())
         * */
        return new ResponseEntity<>(memberService.getOneself(Long.valueOf(uid),status),HttpStatus.OK);
    }

    @Log("查询用户")
    @ApiOperation(value = "查询用户")
    @GetMapping(value = "/yxUser")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_SELECT')")
    public ResponseEntity getYxUsers(YxUserQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(yxUserService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("条件查询用户")
    @ApiOperation(value = "条件查询用户")
    @GetMapping(value = "/yxUserByCondition")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_SELECT')")
    public ResponseEntity getYxUserByCondition(YxUserQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(yxUserService.getUserByCondition(criteria, pageable), HttpStatus.OK);
    }

  /*  @Log("根据分组、层级、父级ID查询用户")
    @ApiOperation(value = "根据分组、层级、父级ID查询用户")
    @RequestMapping(value = "/yxUserByTj")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_SELECT')")
    public ResponseEntity yxUserByTj(YxUserQueryCriteria criteria){
        System.err.println("红的");
//yxUserService.queryAll(criteria,pageable)

        List<YxUser> list = yxUserService.lambdaQuery().eq(YxUser::getGroupId, criteria.getGroupId()).list();


        Map<String, List<YxUser>> collect = list.stream().collect(Collectors.groupingBy((e) -> e.getRealName()));

        collect.forEach((key,value)->{
            System.out.println(key);
            value.forEach((e)->e.getPartnerId());
        });

        return new ResponseEntity<>( yxUserService.lambdaQuery().eq(YxUser::getRealName, criteria.getRealName())
                .eq(YxUser::getGroupId, criteria.getGroupId()),HttpStatus.OK);
    }*/


    @Log("修改用户")
    @ApiOperation(value = "修改用户")
    @PutMapping(value = "/yxUser")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YxUser resources) {
        yxUserService.saveOrUpdateUser(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    @Log("删除用户")
    @ApiOperation(value = "删除用户")
    @DeleteMapping(value = "/yxUser/{uid}")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_DELETE')")
    public ResponseEntity delete(@PathVariable Integer uid) {
        yxUserService.removeById(uid);
        return new ResponseEntity(HttpStatus.OK);
    }


    @ApiOperation(value = "用户禁用启用")
    @PostMapping(value = "/yxUser/onStatus/{id}")
    public ResponseEntity onStatus(@PathVariable Long id, @RequestBody String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Integer status = jsonObject.getInteger("status");
        yxUserService.onStatus(id, status);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "修改余额")
    @PostMapping(value = "/yxUser/money")
    @PreAuthorize("hasAnyAuthority('admin','YXUSER_ALL','YXUSER_EDIT')")
    public ResponseEntity updatePrice(@Validated @RequestBody UserMoneyDto param) {
        yxUserService.updateMoney(param);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    /**
     * 根据用户id获取用户信息
     *
     * @param uid
     * @return
     */
    @GetMapping(value = "/yxUser/getUserByUid")
    public YxUser getUserByUid(@RequestParam Long uid) {
        return yxUserService.getById(uid);
    }

    /**
     * 查询所有用户信息
     *
     * @return Map<Long, YxUser>
     */
    @GetMapping(value = "/yxUser/getAllUserMap")
    public Map<Long, YxUser> getUserByUid() {
        List<YxUser> list = yxUserService.list();
        Map<Long, YxUser> yxUserMap = new HashMap<>();
        list.forEach(i -> {
            yxUserMap.put(i.getUid(), i);
        });
        return yxUserMap;
    }

    /*普通会员*/
    public static final Integer LEVEL_ZERO = 0;
    /* 创客一*/
    public static final Integer LEVEL_ONE = 1;
    /*创客2*/
    public static final Integer LEVEL_TOW = 2;
    /*创客3*/
    public static final Integer LEVEL_THREE = 3;
    /*创客4*/
    public static final Integer LEVEL_FOUR = 4;
    /*主任*/
    public static final Integer DIRECTOR = 5;
    /*经理*/
    public static final Integer MANAGER = 6;
    /*总裁*/
    public static final Integer CEO = 7;

    /**
     * 用户升级
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/yxUser/upLevel")
    public void upLevel(YxUser yxUser) {


        //根据yxUser查询用户信息
        YxUser user = yxUserService.getYxUserId(yxUser.getUid());

        List<YxSystemUserTask> list1 = yxSystemUserTaskService.list();

        //根据任务升级表获取到升级任务金额
        LinkedHashMap<Integer, YxSystemUserTask> map =
                //获取 等级任务表所有数据
                list1
                        .stream().collect(Collectors.toMap(
                        (e) -> e.getLevelId(),
                        (e) -> e,
                        (e1, e2) -> e1,
                        LinkedHashMap::new
                ));

        /*累计金额大于 任务所需金额 并且 小于，创客一 ，升级为 创客一*/
        if (user.getAccumulative_amount().compareTo(map.get(LEVEL_ZERO).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(LEVEL_ONE).getNumber()) == -1) {

            //>升级创客一
            yxUserService.lambdaUpdate().eq(YxUser::getUid, yxUser.getUid()).set(YxUser::getLevel, LEVEL_ONE);
            /*获取 当前用户的关系体系所有数据*/
            List<YxUser> list = yxUserService.lambdaQuery().eq(YxUser::getGroupId, yxUser.getGroupId()).list();

            /*用户的关系体系所有数据 转换 map id 为key value 用户数据*/
            LinkedHashMap<Long, YxUser> groupData = list.stream().collect(Collectors.toMap(
                    (e) -> e.getUid(),
                    (e) -> e,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            ));


            /*获取当前用户父级id*/
            Integer parentId = user.getPartnerId();
            /*通过父级id查询当前用户的父级数据*/
            YxUser parentUser = null;

            while (parentId != 0) {
                /*查询父级的数据*/
                parentUser = groupData.get(parentId);
                /*判断父级的等级 是否 小于 当前用户升级后的等级*/
                if (parentUser.getLevel() <= LEVEL_ONE) {
                    yxUserService.lambdaUpdate().eq(YxUser::getUid, parentUser.getUid()).set(YxUser::getLevel, LEVEL_ONE);

                } else {
                    /*父级的数据 key是 数据的父级id value是本身的值*/
                    Map<Integer, List<YxUser>> partnerData = list.stream().collect(Collectors.groupingBy(
                            (e) -> e.getPartnerId()
                    ));


                    /*如果大于 累计当前用户的所有下级 包括当前用户累计金额*/
                    BigDecimal bigDecimal = queryAccumulative(partnerData, parentUser);

                    /*根据累计金额获取到该金额应提升到的等级*/
                    YxUser finalParentUser = parentUser;
                    /*将积累金额的数据遍历判断*/
                    list1.stream()
                            .forEach((e)->{
                                /*获取当前级别标识加一拿到下一个级别标识*/
                                int  father = e.getLevelId() + 1;
                                /*通过级别标识获取对应级别的数据*/
                                YxSystemUserTask yxSystemUserTask = map.get(father);
                                /*判断下一个级别是不是空*/
                                if(ObjectUtil.isNotEmpty(yxSystemUserTask)){
                                    /*不是空 累计金额 大于遍历级别金额 并且小于他上一个级别*/
                                    if(bigDecimal.compareTo(e.getNumber()) != -1 &&
                                            bigDecimal.compareTo(yxSystemUserTask.getNumber()) == -1){
                                        /*获取到当前父级id*/
                                        Long uid = finalParentUser.getUid();
                                        /*更改等级升级*/
                                        yxUserService.lambdaUpdate().eq(YxUser::getUid,uid).set(YxUser::getLevel,e.getLevelId()).update();

                                    }

                                }else{
                                    /*如果没有下一个级别，只需判断 大于这个级别升级*/
                                    if(bigDecimal.compareTo(e.getNumber()) != -1){
                                        /*获取到当前父级id*/
                                        Long uid = finalParentUser.getUid();
                                        /*更改等级升级*/
                                        yxUserService.lambdaUpdate().eq(YxUser::getUid,uid).set(YxUser::getLevel,e.getLevelId()).update();
                                    }
                                }

                            });

                }

                parentId = parentUser.getPartnerId();

            }

            /*累计金额大于 任务所需金额 并且 小于，创客三 ，升级为 创客二*/
        } else if (user.getAccumulative_amount().compareTo(map.get(LEVEL_ONE).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(LEVEL_TOW).getNumber()) == -1) {



        } else if (user.getAccumulative_amount().compareTo(map.get(LEVEL_TOW).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(LEVEL_THREE).getNumber()) == -1) {




        } else if (user.getAccumulative_amount().compareTo(map.get(LEVEL_THREE).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(LEVEL_FOUR).getNumber()) == -1) {






        } else if (user.getAccumulative_amount().compareTo(map.get(LEVEL_FOUR).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(DIRECTOR).getNumber()) == -1) {





        } else if (user.getAccumulative_amount().compareTo(map.get(DIRECTOR).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(MANAGER).getNumber()) == -1) {




        } else if (user.getAccumulative_amount().compareTo(map.get(MANAGER).getNumber()) != -1
                && user.getAccumulative_amount().compareTo(map.get(CEO).getNumber()) == -1) {
        }


        //判断当前用户现在得等级
       /* yxSystemUserTasks.forEach((e) -> {
            if (user.getAccumulative_amount().compareTo(e.getNumber()) != -1  ) {
                boolean update = yxUserService.lambdaUpdate().set(YxUser::getUid, user.getUid()).set(YxUser::getLevel, 1).update();
                //当前用户 查询上级体系
                Integer partnerId = user.getPartnerId();
                ArrayList<YxUser> yxUsers = new ArrayList<>();
                while (partnerId != 0) {
                    //当前用户父级
                    YxUser yxUser1 = yxUserService.lambdaQuery().eq(YxUser::getUid, partnerId).one();
                    partnerId = yxUser1.getPartnerId();
                    YxUser yxUser2 = yxUserService.lambdaQuery().eq(YxUser::getUid, partnerId).one();

                    List<YxSystemUserTask> yxSystemUserTask = list.stream().collect(Collectors.groupingBy((a) -> a.getLevelId())).get(yxUser2.getLevel());

                }
//不做操作
            }
        });
*/
        //拿出当前用户得累计金额与升级金额进行比较 if 累计金额>升级任务金额  则用户上升到对应的等级

        //根据当前用户得推荐人id 与 分组id 获取到 整个体系的用户


        //根据当前用户获取到 推荐人id
        // long fuji = user.getPartnerId();
        // 判断推荐人当前的等级

        // 判断 推荐人 等级 是否》当前用户等级，《则直接升级为当前用户同等级

        //《 根据 当前用户id 获取到当前用户下的整个体系的累计金额

        //判断 当前用户下的整个体系（包含当前用户的累计金额） 是否》当前用户推荐人等级的升级任务金额

        //》 提升等级


    }

    /*封装累计金额计算方法*/
    public BigDecimal queryAccumulative(Map<Integer, List<YxUser>> map, YxUser yxuser) {
        /*累计金额*/
        BigDecimal accumulative = new BigDecimal("0");

        /*下级数据*/
        ArrayDeque<YxUser> yxUserList = new ArrayDeque<>();

        /*添加当前 用户本身的数据*/
        yxUserList.add(yxuser);
        /* 循环 当前用户下级数据*/
        while (!yxUserList.isEmpty()) {
            /*删除并返回 list中的第一条数据*/
            YxUser pop = yxUserList.pop();
            /*获取 删除并返回第一条数据的id 查找他的下级 */
            List<YxUser> yxUsers = map.get(pop.getUid());
            /*计算 下级累计金额*/
            accumulative = accumulative.add(pop.getAccumulative_amount());
            /*判断不等于 null*/
            if (CollectionUtils.isNotEmpty(yxUsers)) {
                /*加入list继续查找下级*/
                yxUserList.addAll(yxUsers);
            }
        }
        /*返回累计的进金额*/
        return accumulative;

    }




    //当前用户 查询上级体系
    //while (fuji != 0){
    //  //当前用户父级
    //  YxUser yxUser1 = yxUserService.lambdaQuery().eq(YxUser::getUid, fuji).one();
    //  fuji = yxUser1.getPartnerId();
    // }

    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal("380");
        BigDecimal bigDecimal2 = new BigDecimal("381");
        BigDecimal bigDecimal3 = new BigDecimal("381");
        System.err.println(bigDecimal.compareTo(bigDecimal2));
        System.err.println(bigDecimal2.compareTo(bigDecimal));
        System.err.println(bigDecimal2.compareTo(bigDecimal3));


    }

    //TODO 导出会员排行榜Excel
    /**
     *  导出会员排行榜Excel
     * @return ResponseEntity
     */
    @AnonymousAccess
    @ApiOperation(value = "导出会员排行榜Excel")
    @PostMapping(value = "/yxUser/exportExcel")
    public void exportExcel(HttpServletResponse response,@RequestBody YxMemberRankingQueryCriteria user){
        memberService.download(user,response);
    }

    //TODO 排行榜查询
    /**
     * 会员排行榜查询
     * 查询条件：会员级别、业绩、佣金收入进行排行（时间段筛选排行，级别按照升级先后顺序进行排行）
     */
    @AnonymousAccess
    @ApiOperation(value = "会员排行榜查询")
    @PostMapping(value = "/yxUser/query_memberRanking")
    public ResponseEntity memberRanking(@RequestBody  YxMemberRankingQueryCriteria qc){
        return new ResponseEntity<>(memberService.queryMember(qc),HttpStatus.OK);
    }







}
